package config

import (
	"os"
	"time"

	"gopkg.in/yaml.v3"
)

type Duration struct {
	time.Duration
}

func (d *Duration) UnmarshalText(text []byte) error {
	var err error
	d.Duration, err = time.ParseDuration(string(text))
	return err
}

type ListenConfig struct {
	UDP  string `yaml:"udp"`
	GRPC string `yaml:"grpc"`
}

type Peer struct {
	ID string `yaml:"id"`
	IP string `yaml:"ip"`
}

type PriorityConfig struct {
	Base           int `yaml:"base"`
	WeightPerCheck int `yaml:"weight_per_check"`
}

type CheckerConfig struct {
	Type     string   `yaml:"type"`
	Name     string   `yaml:"name"`
	Host     string   `yaml:"host"`
	Port     int      `yaml:"port,omitempty"`
	Username string   `yaml:"username,omitempty"`
	Password string   `yaml:"password,omitempty"`
	Query    string   `yaml:"query,omitempty"`
	Timeout  Duration `yaml:"timeout"`
	Interval Duration `yaml:"interval"`
}

type MonitorConfig struct {
	Enabled bool `yaml:"enabled"`
	Port    int  `yaml:"port"`
}

type Config struct {
	NodeID    string          `yaml:"node_id"`
	Listen    ListenConfig    `yaml:"listen"`
	VIP       string          `yaml:"vip"` // 支持 192.168.1.200/24 或 192.168.1.200/24@eth0:1
	Interface string          `yaml:"interface"`
	Peers     []Peer          `yaml:"peers"`
	Priority  PriorityConfig  `yaml:"priority"`
	Checkers  []CheckerConfig `yaml:"checkers"`
	Monitor   MonitorConfig   `yaml:"monitor"`
}

func Load(path string) (*Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	var cfg Config
	if err := yaml.Unmarshal(data, &cfg); err != nil {
		return nil, err
	}
	return &cfg, nil
}
